package com.http2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Http2Server {
    private Selector selector;
    private Map<Integer, ByteArrayOutputStream> streamBuffers = new ConcurrentHashMap<>(); // 线程安全Map
    private Map<Integer, SocketChannel> streamChannels = new ConcurrentHashMap<>(); // 记录Stream ID与Channel的映射

    public void start() throws Exception {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.bind(new InetSocketAddress(8080));
        serverChannel.configureBlocking(false);
        
        selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
            while (keys.hasNext()) {
                SelectionKey key = keys.next();
                keys.remove();
                
                if (key.isAcceptable()) {
                    SocketChannel clientChannel = serverChannel.accept();
                    clientChannel.configureBlocking(false);
                    clientChannel.register(selector, SelectionKey.OP_READ);
                } 
                else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = channel.read(buffer);
                    if (bytesRead == -1) {
                        channel.close();
                        continue;
                    }
                    buffer.flip();
                    
                    while (buffer.remaining() >= 10) { // HTTP/2帧头最小9字节
                        Http2Frame frame = Http2Frame.deserialize(buffer);
	                    int streamId = frame.streamId;
	                    System.out.println("接收数据：" + new String(frame.payload) + " Stream " + streamId);
	                    
	                    // 按Stream ID分发数据
	                    streamBuffers.computeIfAbsent(streamId, k -> new ByteArrayOutputStream())
	                                .write(frame.payload);
	                    streamChannels.put(streamId, channel); // 记录Stream ID与Channel的映射
	                    // 模拟响应（简化版HEADERS帧）
	                    if (frame.type == 0x1) { // HEADERS帧
	                    	Http2Frame response = new Http2Frame();
	                    	response.streamId = streamId;
	                    	response.type = 0x1;
	                    	response.payload = ("HTTP/2 200 OK for Stream " + streamId).getBytes();
	                    	response.length = response.payload.length;
	                    	
	                    	// 通过记录的Channel发送响应
	                    	SocketChannel targetChannel = streamChannels.get(streamId);
	                    	if (targetChannel != null) {
	                    		targetChannel.write(response.serialize());
	                    		System.out.println("回复数据：" + new String(response.payload));
	                    		key.interestOps(SelectionKey.OP_READ);
	                    	}
	                    }
                    }
                }
            }
        }
    }
    
    public static void main(String[] args) {
        Http2Server server = new Http2Server();
        try {
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}